<template>
    <div style="height: 100%; width: 100%;">
        <div id="x-spread-sheet" style="height: 100%; width: 100%;" />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import SpreadSheet from './SpreadSheet';
const xs = ref();
const cellFragment = ref()
const cellFragmentDataset = ref();

const currentCell = ref()
const FRAGMENT_COLOR = [
    'rgba(83,109,186,0.5)',
    'rgba(165,200,148,0.5)',
    'rgba(250,200,88,0.5)',
    'rgba(238,102,102,0.5)',
    'rgba(115,192,222,0.5)',
    'rgba(59,162,114,0.5)',
    'rgba(252,132,82,0.5)',
    'rgba(154,96,180,0.5)',
    'rgba(234,124,204,0.5)',
];
const PrintCellType = [
    {
        id: 1,
        name: '绑定字段',
        symbol: 'COLUMN',
    },
    {
        id: 2,
        name: '图片',
        symbol: 'IMAGE',
    },
    {
        id: 3,
        name: '条形码',
        symbol: 'BARCODE',
    },
    {
        id: 4,
        name: '二维码',
        symbol: 'QRCODE',
    },
];

function getDictLbael(type) {
    let index = PrintCellType.findIndex(item => item.symbol === type);
    if (index != -1) {
        return PrintCellType[index].id;
    } else {
        return 1;
    }
}

onMounted(() => {
    let spreadSheet = new SpreadSheet('#x-spread-sheet', {
        mode: 'edit', // edit | read
        showToolbar: true,
        showGrid: true,
        showContextmenu: true,
        view: {
            height: () => document.documentElement.clientHeight,
            width: () => document.documentElement.clientWidth,
        },
        row: {
            len: 50,
            height: 25,
        },
        col: {
            len: 26,
            width: 100,
            indexWidth: 60,
            minWidth: 60,
        },
        style: {
            bgcolor: '#ffffff',
            align: 'left',
            valign: 'middle',
            textwrap: false,
            strike: false,
            underline: false,
            color: '#0a0a0a',
            font: {
                name: 'Helvetica',
                size: 10,
                bold: false,
                italic: false,
            },
        },
    });
    xs.value = spreadSheet;
    xs.value.on('cell-selected', (cell: any, ri: number, ci: number) => {
        console.log(`我是第${1}步`);
        let value, temp;
        let columnObject: any = {
            columnName: undefined,
            fieldType: undefined,
            datasetId: undefined,
            relationId: undefined,
            bindDataset: undefined,
            imageSourceType: 1,
            datasetType: undefined,
        };
        console.log("我执行了", columnObject, cell, ri, ci)
        if (cell != null) {
            try {
                temp = JSON.parse(cell.v);
                if (temp != null && temp.value != null) {
                    value = temp.value;
                } else {
                    value = cell.v;
                }
                // 单元格数据类型为绑定字段
                if (
                    temp != null &&
                    (temp.cellType === getDictLbael('COLUMN') ||
                        temp.cellType === getDictLbael('BARCODE') ||
                        temp.cellType === getDictLbael('QRCODE') ||
                        temp.cellType === getDictLbael('IMAGE'))
                ) {
                    columnObject = {
                        columnName: temp.columnName,
                        fieldType: temp.fieldType,
                        datasetId: temp.datasetId,
                        relationId: temp.relationId,
                        bindDataset: temp.relationId || temp.datasetId,
                        imageSourceType: 1,
                        barCodeType:
                            temp.barCodeType,

                        barCodeShowWords: temp.barCodeShowWords || false,
                        datasetType: temp.datasetType,
                    };
                }
            } catch (e) {
                temp = null;
                value = cell.v;
            }
        }
        currentCell.value = {
            position: { r: ri, c: ci },
            cellType: (temp || {}).cellType || getDictLbael('COLUMN'),
            cell: cell,
            value: value,
            ...columnObject,
        };
        console.log(currentCell)
        // 
        xs.value.on('cell-edited', (text: string, ri: number, ci: number) => {

            if (currentCell.value.position.r + '-' + currentCell.value.position.c === ri + '-' + ci) {

                // TODO 这里原使用的是this.columnName与`{${text}}`进行的比较
                if (
                    `{${text}}` !== currentCell.value.columnName &&
                    currentCell.value.columnName !== undefined
                ) {
                    currentCell.value.columnName = undefined;
                    // currentCell.value.cell = undefined
                    currentCell.value.datasetType = undefined;
                    currentCell.value.fieldType = undefined;
                    currentCell.value.relationId = undefined;
                    currentCell.value.value = undefined;
                }
                let tmp = { ...currentCell.value.cell, text: text };
                if (tmp.v) {
                    delete tmp.v;
                }
                console.log(tmp);
                xs.value.setCellValue(currentCell.value.position.r, currentCell.value.position.c, tmp);
            }
            // console.log(text, ri, ci, 'text-edit', currentCell.value)
        });
    })
});
const findFragment = (rowNum: number) => {
    let fragmentInfo = null;
    return fragmentInfo;
};
/**
 * 单元格绑定数据改变
 */
 const onCellValueChange = (val: string | undefined = undefined) => {
  console.log(`我是第${2}步`);
  if (currentCell.value && currentCell.value.position && val) {
    let cellValue: string | undefined = val;
    let columnPath = findCellBindColumnPath(val);
    let column = Array.isArray(columnPath) ? columnPath[columnPath.length - 1] : columnPath;
    if (
      currentCell.value.cellType === getDictLbael('COLUMN') ||
      currentCell.value.cellType === getDictLbael('BARCODE') ||
      currentCell.value.cellType === getDictLbael('QRCODE')
    ) {
      if (currentCell.value.columnName == null) {
        cellValue = undefined;
      } else {
        cellValue = JSON.stringify({
          cellType: currentCell.value.cellType,
          value: val,
          datasetId: (cellFragment.value || {}).datasetId,
          relationId:
            (cellFragmentDataset.value || {}).datasetType !== DatasetType.API
              ? currentCell.value.relationId
              : undefined,
          columnName: currentCell.value.columnName,
          fieldType: column ? column.fieldType : undefined,
          barCodeType:
            currentCell.value.cellType === PrintCellType.BARCODE ||
            currentCell.value.cellType === PrintCellType.QRCODE
              ? currentCell.value.barCodeType
              : undefined,
          barCodeShowWords:
            currentCell.value.cellType === PrintCellType.BARCODE
              ? currentCell.value.barCodeShowWords
              : undefined,
          datasetType: (cellFragmentDataset.value || {}).datasetType,
        });
      }
    } else if (currentCell.value.cellType === PrintCellType.IMAGE) {
      if (currentCell.value.columnName == null) {
        cellValue = undefined;
      } else {
        cellValue = JSON.stringify({
          cellType: currentCell.value.cellType,
          imageSourceType: currentCell.value.imageSourceType,
          value: val,
          datasetId: (cellFragment.value || {}).datasetId,
          relationId:
            (cellFragmentDataset.value || {}).datasetType !== DatasetType.API
              ? currentCell.value.relationId
              : undefined,
          columnName: currentCell.value.columnName,
          fieldType: column ? column.fieldType : undefined,
          barCodeType: undefined,
          barCodeShowWords: undefined,
          datasetType: (cellFragmentDataset.value || {}).datasetType,
        });
      }
    }
    console.log(val);
    let m;
    if (val == null || val === '') {
      m = '';
    } else {
      if (
        [
          PrintCellType.COLUMN,
          PrintCellType.BARCODE,
          PrintCellType.QRCODE,
          PrintCellType.IMAGE,
        ].indexOf(currentCell.value.cellType) !== -1
      ) {
        m = Array.isArray(val) ? val.join(' / ') : val;
        if (m !== '') m = `{${m}}`;
      }
    }
    console.log(val, m, ']]]]]');
    xs.value.setCellValue(currentCell.value.position.r, currentCell.value.position.c, {
      ...currentCell.value.cell,
      v: cellValue == null ? '' : cellValue,
      text: m,
    });
  }
};
</script>


<style scoped></style>